<?php

namespace JsonLowCode;

use JsonLowCode\Helps\Js;
use JsonLowCode\Traits\HasMake;
use RuntimeException;

abstract class JsBase
{

    use HasMake;

    protected string $script = "";

    /**
     * @var bool 是否函数包裹
     */
    protected bool $isFunction = false;

    /**
     * @param string|array $to
     * @return Js
     */
    protected function jsFrom(string|array $to): Js
    {
        try {
            $to = Js::from($to);
        } catch (\JsonException $e) {
            throw new RuntimeException($e->getMessage());
        }
        return $to;
    }

    /**
     * @param bool $bool
     * @return $this
     */
    public function setJsFunction(bool $bool = false): static
    {
        $this->isFunction = $bool;
        return $this;
    }

    /**
     * @param $closure
     * @return $this
     */
    protected function callback($closure): static
    {
        if ($closure!=null) $closure($closure,$this);
        return $this;
    }

    protected function toString(): string
    {
        if ($this->isFunction){
            return scriptFunc($this->script);
        }else{
            return $this->script;
        }
    }
}
